# coding=UTF-8
"""
导出excel
export_excel(title,columns=[],data_list=[])
title:标题
columns：列头字段
data_list：数据
"""
from django.shortcuts import render_to_response
from django.template import RequestContext


def export_excel_template(request, filename='', columns=[], data_list=[], template='backend/export/export_model.html'):
    '''
    使用前端模板导出excel
    :param filename: 
    :param columns: 
    :param data_list: 
    :return: 
    '''
    model_data = []
    for model in data_list:
        temp = []
        for column in columns:
            temp.append({
                'value': model[column['key']] or '',
                'style': column.get('style', '')
            })
        model_data.append({
            'data': temp,
            'style': ''
        })

    response = render_to_response(
        template,
        {
            'data': model_data,
            'columns': columns
        },
        content_type='application/vnd.ms-excel'
    )
    response.charset = 'utf-8'
    header_value = 'attachment;filename=%s.xls' % filename
    header_value = header_value.encode('utf-8')
    response._headers.update({
        'content-disposition': ('Content-Disposition', header_value)
    })
    return response